/**
 * 3*3 矩阵
 * @author zzhanglin
 * @param a
 * @param b
 * @param c
 * @param d
 * @param tx
 * @param ty
 */
Matrix = function(a, b, c, d, tx, ty) 
{
    this._a = a !== undefined ? a : 1;
    this._b =  b || 0 ;
    this._c =  c || 0 ;
    this._d = d !== undefined ? d : 1;
    this._tx = tx || 0 ;
    this._ty=  ty || 0 ;
} ;

/**
 * 调用 identity() 方法后，生成的矩阵具有以下属性：a=1、b=0、c=0、d=1、tx=0 和 ty=0。
 */
Matrix.prototype.identity = function(){
	  this._a = 1;
	  this._b =  0 ;
	  this._c =   0;
	  this._d =  1;
	  this._tx = 0 ;
	  this._ty=   0 ;
	  return this ;
};

/**
 * 矩阵叠加
 * @param matrix
 */
Matrix.prototype.concat = function(matrix) {
  var m11 = this._a * matrix._a + this._c * matrix._b;
  var m12 = this._b * matrix._a + this._d * matrix._b;

  var m21 = this._a * matrix._c + this._c * matrix._d;
  var m22 = this._b * matrix._c + this._d * matrix._d;

  var dx = Math.abs(this._a) * matrix._tx + this._c * matrix._ty + this._tx;
  var dy = Math.abs(this._b) * matrix._tx + this._d * matrix._ty + this._ty;

  this._a = m11;
  this._b = m12;
  this._c = m21;
  this._d = m22;
  this._tx = dx;
  this._ty = dy;
};

/**
 * 翻转矩阵
 */
Matrix.prototype.inverse = function() {
  var d = 1 / (this._a * this._d - this._b * this._c);
  var m0 = this._d * d;
  var m1 = -this._b * d;
  var m2 = -this._c * d;
  var m3 = this._a * d;
  var m4 = d * (this._c * this._ty - this._d * this._tx);
  var m5 = d * (this._b * this._tx - this._a * this._ty);
  this._a = m0;
  this._b = m1;
  this._c = m2;
  this._d = m3;
  this._tx = m4;
  this._ty = m5;
};

/**
 * 旋转
 * @param rad 弧度
 */
Matrix.prototype.rotate = function(rad) {
  var c = Math.cos(rad);
  var s = Math.sin(rad);
  var m11 = this._a * c + this._c * s;
  var m12 = this._b * c + this._d * s;
  var m21 = this._a * -s + this._c * c;
  var m22 = this._b * -s + this._d * c;
  this._a = m11;
  this._b = m12;
  this._c = m21;
  this._d = m22;
};

/**
 * 移动一段距离
 */
Matrix.prototype.translate = function(x, y) {
  this._tx += this._a * x + this._c * y;
  this._ty += this._b * x + this._d * y;
};

/**
 * 缩放
 * @param sx
 * @param sy
 */
Matrix.prototype.scale = function(sx, sy) {
  this._a *= sx;
  this._b *= sx;
  this._c *= sy;
  this._d *= sy;
};

/**
 * 转换点
 */
Matrix.prototype.transformPoint = function(px, py) {
  return new Point(
		  this._a *px + this._c * py + this._tx ,  
		  this._b * px + this._d * py + this._ty 
		  ) ;
};

Matrix.prototype.deltaTransformPoint = function(point) {
    return new Point(
      this._a * point.x + this._c * point.y,
      this._b * point.x + this._d * point.y
    );
};

Matrix.prototype.clone = function(){
	return new Matrix(this._a,this._b,this._c,this._d,this._tx,this._ty);
};